package com.rzico.sbl.ui.member

import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberBucketBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.BucketData
import com.rzico.sbl.model.CommonData
import com.xinnuo.common.decoration.DividerLRDecoration
import com.rzico.sbl.other.showBucketDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.BucketViewModel
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MemberBucketActivity : BaseActivity(R.layout.activity_member_bucket) {

    private val mBinding by lazy { ActivityMemberBucketBinding.bind(getRootView()) }

    private val mBrandList = ArrayList<CommonData>()
    private lateinit var mCardId: String
    private lateinit var mMemberId: String

    override fun getViewModel() = get<BucketViewModel>()

    override fun initData() {
        initTitle(title = "空桶押金")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData()
    }

    private fun initLayout() {
        when (userRole) {
            // 店主、管理员
            "1" -> {
                mMemberId.notEmpty {
                    mBinding.bucketBottom.visible()
                }
            }
        }

        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关空桶信息！"
                }

                recycleList.also {
                    it.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData() }
                    )

                    it.addItemDecoration(DividerLRDecoration(bottom = 50f))
                    it.addOnScrollChanged(
                        onShow = { mBinding.bucketBottom.bottomShow() },
                        onHide = { mBinding.bucketBottom.bottomHide(52f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<BucketData>(R.layout.item_bucket_list) { jector, bean, _ ->
                            jector.text(R.id.item_bucket_name, bean.name)
                                .text(R.id.item_bucket_ya, bean.mortgage)
                                .text(R.id.item_bucket_jie, bean.borrow)
                                .text(R.id.item_bucket_hang, bean.hang)

                                .clicked {
                                    startActivityEx<MemberBucketRecordActivity>(
                                        "cardId" to mCardId,
                                        "barrelId" to bean.barrelId
                                    )
                                }
                        }
                        .attachTo(it)
                }
            }
    }

    override fun initListener() {
        mCardId = intent.getExtra("cardId")
        mMemberId = intent.getExtra("memberId")

        mBinding
            .bucketManager
            .oneClick {
                showActionDialog("押桶", "退桶", "借桶", "还桶") { index, _ ->
                    // 协程延时
                    lifecycleScope.launch {
                        // 挂起函数
                        delay(400)

                        when (index) {
                            0 -> getBrandList { showPledgeDialog() }
                            1 -> showBackDialog()
                            2 -> getBrandList { showBorrowDialog() }
                            3 -> getBrandList { showReturnDialog() }
                        }
                    }
                }
            }
    }

    /**
     * 押桶
     */
    private fun pledgeBucket(
        brandId: String,
        num: String,
        money: String
    ) {
        getViewModel()
            .bucketEidt(
                BaseUrl.bucketAdd,
                "memberId" to mMemberId,
                "barrelId" to brandId,
                "quantity" to num,
                "pledge" to money,
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("押桶成功！")

                    // 更新空桶
                    LiveEventBus
                        .get("bucketModify")
                        .post("refresh")

                    updateList()
                }
            )
    }

    /**
     * 借桶
     */
    private fun borrowBucket(
        brandId: String,
        num: String,
        hint: String
    ) {
        getViewModel()
            .bucketEidt(
                BaseUrl.bucketBrw,
                "memberId" to mMemberId,
                "barrelId" to brandId,
                "quantity" to num,
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast(hint)

                    // 更新空桶
                    LiveEventBus
                        .get("bucketModify")
                        .post("refresh")

                    updateList()
                }
            )
    }

    /**
     * 退桶
     */
    private fun backBucket(
        brandId: String,
        num: String,
        money: String
    ) {
        getViewModel()
            .bucketEidt(
                BaseUrl.bucketdel,
                "memberId" to mMemberId,
                "barrelId" to brandId,
                "quantity" to num,
                "pledge" to money,
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("退桶成功！")

                    // 更新空桶
                    LiveEventBus
                        .get("bucketModify")
                        .post("refresh")

                    updateList()
                }
            )
    }

    /**
     * 桶品牌列表
     */
    private fun getBrandList(onFinish: () -> Unit) {
        mBrandList
            .isNotEmpty()
            .conditionElse(
                actionTrue = onFinish,
                actionFalse = {
                    getViewModel()
                        .requestCommon(
                            isLoading = true,
                            requestUrl = BaseUrl.bucketPdt,
                            requestMethod = HttpMethod.GET,
                            onSuccess = {
                                mBrandList.clear()
                                mBrandList.addItems(it)
                            },
                            onFinally = onFinish
                        )
                }
            )
    }

    /**
     * 空桶押金列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .bucketList(
                cardId = mCardId,
                onSuccess = {
                    mBinding.bucketNum.text = it.stock
                    mBinding.bucketTotal.text = it.pledge.formatDecimal()

                    mList.apply {
                        clear()
                        addItems(it.data)
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 更新列表
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

    /**
     * 押桶提示框
     */
    private fun showPledgeDialog() {
        showListDialog(
            title = "请选择品牌",
            items = mBrandList.map { it.name.orEmpty() },
            listener = { index, hint ->
                mPosition = index

                showBucketDialog(
                    name = hint,
                    type = 1,
                    isForced = true,
                    defaultPrice = mBrandList[mPosition].pledge.orEmpty("0"),
                    onDismiss = { mPosition = -1 },
                    onSure = { num, money ->
                        pledgeBucket(mBrandList[mPosition].id, num, money)
                    },
                    onSelect = { text, priceArr ->
                        showListDialog(
                            title = "请选择品牌",
                            items = mBrandList.map { it.name.orEmpty() },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index
                                text.text = hint
                                priceArr[0] = mBrandList[mPosition].pledge.doubleValue
                            }
                        )
                    }
                )
            }
        )
    }

    /**
     * 借桶提示框
     */
    private fun showBorrowDialog() {
        showListDialog(
            title = "请选择品牌",
            items = mBrandList.map { it.name.orEmpty() },
            listener = { index, hint ->
                mPosition = index

                showBucketDialog(
                    name = hint,
                    type = 2,
                    isForced = true,
                    onDismiss = { mPosition = -1 },
                    onSure = { num, _ ->
                        borrowBucket(mBrandList[mPosition].id, num, "借桶成功！")
                    },
                    onSelect = { text, _ ->
                        showListDialog(
                            title = "请选择品牌",
                            items = mBrandList.map { it.name.orEmpty() },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index
                                text.text = hint
                            }
                        )
                    }
                )
            }
        )
    }

    /**
     * 退桶提示框
     */
    private fun showBackDialog() {
        mList.none {
            (it as BucketData).mortgage.intValue > 0
        }.condition {
            showToast("暂无可退空桶")
            return
        }

        val filterList = mList.filter {
            (it as BucketData).mortgage.intValue > 0
        }

        showListDialog(
            title = "请选择品牌",
            items = filterList.map { (it as BucketData).name },
            listener = { index, hint ->
                mPosition = index

                showBucketDialog(
                    name = hint,
                    type = 3,
                    isForced = true,
                    defaultPrice = (filterList[mPosition] as BucketData).barrelPledge,
                    onDismiss = { mPosition = -1 },
                    onSure = { num, money ->
                        backBucket((filterList[mPosition] as BucketData).barrelId, num, money)
                    },
                    onSelect = { text, priceArr ->
                        showListDialog(
                            title = "请选择品牌",
                            items = filterList.map { (it as BucketData).name },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index
                                text.text = hint
                                priceArr[0] =
                                    (filterList[mPosition] as BucketData)
                                        .barrelPledge
                                        .doubleValue
                            }
                        )
                    }
                )
            }
        )
    }

    /**
     * 还桶提示框
     */
    private fun showReturnDialog() {
        showListDialog(
            title = "请选择品牌",
            items = mBrandList.map { it.name.orEmpty() },
            listener = { index, hint ->
                mPosition = index

                showBucketDialog(
                    name = hint,
                    type = 4,
                    isForced = true,
                    onDismiss = { mPosition = -1 },
                    onSure = { num, _ ->
                        borrowBucket(mBrandList[mPosition].id, "-$num", "还桶成功！")
                    },
                    onSelect = { text, _ ->
                        showListDialog(
                            title = "请选择品牌",
                            items = mBrandList.map { it.name.orEmpty() },
                            index = mPosition,
                            listener = { index, hint ->
                                mPosition = index
                                text.text = hint
                            }
                        )
                    }
                )
            }
        )
    }

}